package com.jhws.business.face.service;

import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.business.face.bo.FaceConstant;
import com.jhws.business.face.bo.FaceInfo;
import com.jhws.business.local.bo.LocalConstant;
import com.jhws.business.local.service.LocalService;
import com.jhws.business.owner.bo.TblOwnerDimBo;
import com.jhws.business.owner.service.ITblOwnerDimService;
import com.jhws.core.db.BaseDao;

import com.jhws.util.GetId;
import com.jhws.util.ObjectUtils;
import com.jhws.util.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class FaceService {
    @Resource
    private BaseDao BaseDao;
    @Resource
    private ITblOwnerDimService IOwnerService;
    @Resource
    private FaceAsyncService asyncService;
    @Resource
    private OSSClientService ossClientService;
    @Resource
    private LocalService localService;

    /**
     * 保存人脸信息
     *
     * @param faceInfo
     * @return
     * @throws Exception
     */
    public FaceInfo saveFaceInfo(FaceInfo faceInfo) throws Exception {
        List<FaceInfo> faceInfos = getFaceInfosByWhere("where owner_code = '" + faceInfo.getOwnerCode() + "'", false);
        TblOwnerDimBo ownerDimBo = IOwnerService.findTblOwnerDimById(faceInfo.getOwnerCode());
        //局域网不处理
        if (!localService.isLanMode()) {
            //拷贝人脸图片
            String fileName = FilenameUtils.getName(faceInfo.getImageUrl());
            String destKey = "comm/" + ownerDimBo.getCommCode() + "/face/" + fileName;
            ossClientService.gerneralCopyFile(faceInfo.getImageUrl(), destKey);
            faceInfo.setImageUrl(destKey);
            //拷贝人脸特征
            fileName = FilenameUtils.getName(faceInfo.getFaceFeature());
            destKey = "comm/" + ownerDimBo.getCommCode() + "/face/" + fileName;
            ossClientService.gerneralCopyFile(faceInfo.getFaceFeature(), destKey);
            faceInfo.setFaceFeature(destKey);
        }
        //更新时间
        Date date = new Date();
        //如果存在只更新时间
        if (faceInfos != null && faceInfos.size() > 0) {
            for (FaceInfo f : faceInfos) {
                f.setDate(date);
                f.setAge(faceInfo.getAge());
                f.setSex(faceInfo.getSex());
                f.setImageUrl(faceInfo.getImageUrl());
                f.setFaceFeature(faceInfo.getFaceFeature());
                f.setTimestamp(date.getTime());
                f.setCommCode(ownerDimBo.getCommCode());
                f.setBuilding(ownerDimBo.getAreaCode());
                f.setUnit(ownerDimBo.getBuildingCode());
                f.setIsSynch(LocalConstant.SYNCH_STATE_NO);
                BaseDao.h().update(f);
            }
        } else {
            faceInfo.setCommCode(ownerDimBo.getCommCode());
            faceInfo.setBuilding(ownerDimBo.getAreaCode());
            faceInfo.setUnit(ownerDimBo.getBuildingCode());
            faceInfo.setDate(date);
            faceInfo.setTimestamp(date.getTime());
            faceInfo.setIsSynch(LocalConstant.SYNCH_STATE_NO);
            if (StringUtils.isEmpty(faceInfo.getId())) {
                faceInfo.setId(GetId.randomID());
            }
            faceInfo.setParentId("0");
            BaseDao.h().save(faceInfo);
            faceInfos = new ArrayList<>();
            faceInfos.add(faceInfo);
        }
        long time = date.getTime();
        asyncService.push(time, ownerDimBo.getCommCode(), faceInfos);
        return faceInfo;
    }

    /**
     * 添加人脸识别权限
     *
     * @param ownerCode
     * @param building
     * @param unit
     * @return
     */
    public FaceInfo addFaceAuth(String ownerCode, String building, String unit) throws Exception {
        //先删除
        deleteFaceInfoByWhere("where owner_code ='" + ownerCode +
                        "' and building = '" + building +
                        "' and unit = '" + unit +
                        "' and state ='" + FaceConstant.STATE_CODE.delete.ordinal() + "'",
                false);

        List<FaceInfo> faceInfos = getFaceInfosByWhere("where owner_code = '" + ownerCode + "' and parent_id = '0'", false);
        if (faceInfos != null && faceInfos.size() > 0) {
            Date date = new Date();
            FaceInfo faceInfo = new FaceInfo();
            ObjectUtils.copyPropertiesIgnoreNull(faceInfos.get(0), faceInfo);
            faceInfo.setBuilding(building);
            faceInfo.setUnit(unit);
            faceInfo.setDate(date);
            faceInfo.setTimestamp(date.getTime());
            faceInfo.setParentId(faceInfo.getId());
            faceInfo.setId(GetId.randomID());
            faceInfo.setIsSynch(LocalConstant.SYNCH_STATE_NO);
            BaseDao.h().save(faceInfo);
            long time = date.getTime();
            asyncService.push(time, faceInfo.getCommCode(), Collections.singletonList(faceInfo));
            return faceInfo;
        }
        return null;
    }

    /**
     * 更新状态
     *
     * @param id
     * @param state
     * @throws Exception
     */
    public void updateFaceState(String id, int state) throws Exception {
        FaceInfo faceInfo = BaseDao.get(FaceInfo.class, id);
        Date date = new Date();
        faceInfo.setDate(date);
        faceInfo.setTimestamp(date.getTime());
        faceInfo.setState(state);
        faceInfo.setIsSynch(LocalConstant.SYNCH_STATE_NO);
        BaseDao.h().update(faceInfo);
        long time = date.getTime();
        asyncService.push(time, faceInfo.getCommCode(), Collections.singletonList(faceInfo));
    }

    /**
     * 根据ownerCode更新状态
     *
     * @throws Exception
     */
    public void updateFacesState(String ownerCode, int state) throws Exception {
        List<FaceInfo> faceInfos = getFaceInfosByWhere("where owner_code = '" + ownerCode + "'", false);
        if (faceInfos != null && faceInfos.size() > 0) {
            Date date = new Date();
            for (FaceInfo faceInfo : faceInfos) {
                faceInfo.setDate(date);
                faceInfo.setTimestamp(date.getTime());
                faceInfo.setState(state);
                faceInfo.setIsSynch(LocalConstant.SYNCH_STATE_NO);
                BaseDao.h().update(faceInfo);
            }
            long time = date.getTime();
            asyncService.push(time, faceInfos.get(0).getCommCode(), faceInfos);
        }
    }

    /**
     * 条件获取人脸信息
     *
     * @param where
     * @return
     */
    public List<FaceInfo> getFaceInfosByWhere(String where, boolean isUrl) {
        List<FaceInfo> faceInfos = BaseDao.findList("from FaceInfo " + where);
        if (faceInfos != null && faceInfos.size() > 0) {
            if (!isUrl) {
                return faceInfos;
            }
            for (FaceInfo faceInfo : faceInfos) {
                faceInfo.setImageUrl(ossClientService.getUrl(faceInfo.getImageUrl(), false));
                faceInfo.setFaceFeature(ossClientService.getUrl(faceInfo.getFaceFeature(), false));
            }
            return faceInfos;
        }
        return null;
    }

    /**
     * 删除人脸信息
     *
     * @param where
     */
    public void deleteFaceInfoByWhere(String where, boolean isDeleteOss) throws Exception {
        if (localService.isLanMode()) {
            //删除本地的图片和人脸信息
            List<FaceInfo> faceInfos = BaseDao.findList("from FaceInfo " + where);
            if (faceInfos != null && faceInfos.size() > 0) {
                if (isDeleteOss) {
                    for (FaceInfo faceInfo : faceInfos) {
                        File file = localService.getFile(faceInfo.getImageUrl());
                        if (file != null) {
                            file.delete();
                        }
                        file = localService.getFile(faceInfo.getFaceFeature());
                        if (file != null) {
                            file.delete();
                        }
                    }
                }
                BaseDao.executeHql("update FaceInfo set is_synch='" + LocalConstant.SYNCH_STATE_DEL + "'" + where);
            }
        } else {
            //删除oss上的图片和人脸信息
            List<FaceInfo> faceInfos = BaseDao.findList("from FaceInfo " + where);
            if (faceInfos != null && faceInfos.size() > 0) {
                if (isDeleteOss) {
                    for (FaceInfo faceInfo : faceInfos) {
                        ossClientService.deleteObject(faceInfo.getImageUrl());
                        ossClientService.deleteObject(faceInfo.getFaceFeature());
                    }
                }
                String sql = "delete from face_info " + where;
                BaseDao.j().execute(sql);
            }
        }
    }


}
